var myApp;
myApp = myApp || (function () {
    var pleaseWaitDiv = $('<div class="pos-modal-backdrop fade in"><div class="pos-loading"  style="display: block;"></div></div>');
     var errorDiv = $('<div class="alert alert-danger alert-dismissible" role="alert" id="model-error-block"  style="display:block;">'+
                     '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                      '<strong>Error!</strong> A problem has been occurred while submitting your data.</div>');

       var successDiv = $('<div class="alert alert-success alert-dismissible" role="alert" id="model-error-block"  style="display:block;">'+
                           '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                            '<strong>Well done!</strong> You successfully read this important alert message..</div>');


    return {
        showPleaseWait: function(posElement) {
             console.log('showPleaseWait:-'+posElement);
            $(posElement).append( pleaseWaitDiv );

        },
         showError: function(posElement) {
             console.log('showError:-'+posElement);
             $(posElement).prepend( errorDiv );
               $( "div.alert-success" ).remove();
         },
         showSuccess: function(posElement) {
              console.log('showSuccess:-'+posElement);
              $(posElement).prepend( successDiv );
              $( "div.alert-danger" ).remove();
         },
        hidePleaseWait: function () {
           console.log('hidePleaseWait');
           $( "div.pos-modal-backdrop" ).remove();
        },

    };
})();


 function resetFormData(formId){

   var inputSelector = ':input:not([type="submit"], button):enabled:visible'

        $('#'+formId).find(inputSelector).each(function( index ) {
               $(this).val('');

           });

 }
 function loadFormData(result,prefix){

            $.each(result, function(key, value) {


             var key1='#';

              if(prefix){
                key1=key1+prefix+'-'+key;

              }else
              key1=key1+key;


              if(jQuery.type(value) == 'object')
               {
                 loadFormData(value,prefix+'-'+key);
               }


              var elementObj=$(key1);

              if( elementObj)
                {
                     if(elementObj.is("input") || elementObj.is("select") || elementObj.is("textarea"))
                        elementObj.val(value);
                     else
                        elementObj.html(value);

                }



                //display the key and value pair
                //alert(k + ' is ' + v);
            });
      }


 function loadModelData(modelId,result){

            $.each(result, function(key, value) {


        var elementObj=$( "#"+modelId ).has( '#'+key );

            //  var elementObj=$('#'+modelId+' > #'+key);

              if( elementObj)
                {
                     if(elementObj.is("input") || elementObj.is("select"))
                        elementObj.val(value);
                     else
                        elementObj.html(value);

                }



                //display the key and value pair
                //alert(k + ' is ' + v);
            });
      }



     function initCurrencyField(){


     }

     function initInputMask(){

             $.applyDataMask();

     }

     function initDateTime(){
            $(".datetimepicker").datetimepicker({ format: 'DD-MMM-YYYY hh:mm a',maxDate:moment() });



     //$('#reportrange span').html(moment().subtract(29, 'days').format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY'));

            $('.pos-daterangepicker').daterangepicker({
                format: 'MM/DD/YYYY',
                startDate: moment().subtract(29, 'days'),
                endDate: moment(),
                minDate: '01/01/2012',
                maxDate: moment() ,
                dateLimit: { days: 60 },
                showDropdowns: true,
                showWeekNumbers: true,
                timePicker: true,
                timePickerIncrement: 30,
                format: 'DD-MMM-YYYY hh:mm a',
                timePicker12Hour: true,
                ranges: {
                   'Today': [moment().startOf('day'), moment()],
                   'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                   'This Week': [moment().startOf('week'), moment()],
                   'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                   'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                   'This Month': [moment().startOf('month'), moment().endOf('month')],
                   'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                   'This Year': [moment().startOf('year'), moment()]
                },
                opens: 'left',
                drops: 'down',
                buttonClasses: ['btn', 'btn-sm'],
                applyClass: 'btn-primary',
                cancelClass: 'btn-default',
                separator: ' to ',
                locale: {
                    applyLabel: 'Submit',
                    cancelLabel: 'Cancel',
                    fromLabel: 'From',
                    toLabel: 'To',
                    customRangeLabel: 'Custom',
                    daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
                    monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                    firstDay: 1
                }
            }, function(start, end, label) {
                console.log(start.toISOString(), end.toISOString(), label);
                $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            });

          }


     $(function(){

        $( "#tabs" ).tabs({
            collapsible: true
        });
            initCurrencyField();
            initDateTime();

            initInputMask();
            initPOSModel();

            initSearch();
          });


function initSearch(){

     var $formObj=$('form.pos-search-form');
        console.log("form value changed");
        var inputSelector = ':input:not([type="submit"], button):enabled:visible'

              $formObj.find(inputSelector).change(function() {
                     var updater=$formObj.data("updater");
                       if(updater){
                              console.log("Updating the Grid:-"+updater);
                           $(updater).trigger("reloadGrid");
                      }
           });
            $formObj.submit(function(event) {
               event.preventDefault();
                                var updater=$formObj.data("updater");
                                  if(updater){
                                  console.log("calling updater:-"+updater);
                                      console.log("Updating the Grid:-"+updater);
                                      $(updater).trigger("reloadGrid");
                                 }
                      });


    }
         function showErrors() {

              $el=$('#name-div');


                var $group = $el.closest('.form-group')
                var $block = $group.find('.help-block.with-errors')
                var $feedback = $group.find('.form-control-feedback')


                errors = $('<ul/>')
                  .addClass('list-unstyled')
                  .append('The product name is invalid')

                $block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
                $block.empty().append(errors)
                $group.addClass('has-error')

                $feedback.length
                  && $feedback.removeClass(this.options.feedback.success)
                  && $feedback.addClass(this.options.feedback.error)
                  && $group.removeClass('has-success')

            }

var cache = {};

function initProductSearch(callbackFunction){

     $( ".search-products" ).autocomplete({
            delay: 500,
                           source: function( request, response ) {

                            var term = request.term;
                            if ( term in cache ) {
                                      var data=   cache[ term ];
                                      response(
                                             $.map(data.products, function(item) {
                                                         return {
                                                          label: item.name,
                                                          value: item.productId,
                                                          product:item,
                                               }
                                        })
                                   );
                                 return;
                              }
                            $.ajax({
                                 url: "../product/search",
                                  dataType: "json",
                                  data: {
                                  query: request.term
                                 },
                                 success: function( data ) {
                                     cache[ term ] = data;
                                   response($.map(data.products, function(item) {

                                                              return {
                                                                label: item.name,
                                                                value: item.productId,
                                                                product:item,
                                                              }
                                                            }));

                                 }
                          }); },
                          minLength: 2,
                          select: callbackFunction

                  }
                  );

 }

 function initGridUI(){

      jQuery(".ui-jqgrid").removeClass("ui-widget ui-widget-content");
                     	jQuery(".ui-jqgrid-view").children().removeClass("ui-widget-header ui-state-default");
                     	jQuery(".ui-jqgrid-labels, .ui-search-toolbar").children().removeClass("ui-state-default ui-th-column ui-th-ltr");
                     	jQuery(".ui-jqgrid-pager").removeClass("ui-state-default");
                     	jQuery(".ui-jqgrid").removeClass("ui-widget-content");

                     	jQuery(".ui-jqgrid-htable").addClass("table table-bordered table-hover");
                     	jQuery(".ui-pg-div").removeClass().addClass("btn btn-sm btn-primary");
                     	jQuery(".ui-icon.ui-icon-plus").removeClass().addClass("fa fa-plus");
                     	jQuery(".ui-icon.ui-icon-pencil").removeClass().addClass("fa fa-pencil");
                     	jQuery(".ui-icon.ui-icon-trash").removeClass().addClass("fa fa-trash-o");
                     	jQuery(".ui-icon.ui-icon-search").removeClass().addClass("fa fa-search");
                     	jQuery(".ui-icon.ui-icon-refresh").removeClass().addClass("fa fa-refresh");
                     	jQuery(".ui-icon.ui-icon-disk").removeClass().addClass("fa fa-save").parent(".btn-primary").removeClass("btn-primary").addClass("btn-success");
                     	jQuery(".ui-icon.ui-icon-cancel").removeClass().addClass("fa fa-times").parent(".btn-primary").removeClass("btn-primary").addClass("btn-danger");

                     	jQuery( ".ui-icon.ui-icon-seek-prev" ).wrap( '<div class="btn btn-sm btn-default"></div>' );
                     	jQuery(".ui-icon.ui-icon-seek-prev").removeClass().addClass("fa fa-backward");

                     	jQuery( ".ui-icon.ui-icon-seek-first" ).wrap( '<div class="btn btn-sm btn-default"></div>');
                     	jQuery(".ui-icon.ui-icon-seek-first").removeClass().addClass("fa fa-fast-backward");

                     	jQuery( ".ui-icon.ui-icon-seek-next" ).wrap( '<div class="btn btn-sm btn-default"></div>' );
                     	jQuery(".ui-icon.ui-icon-seek-next").removeClass().addClass("fa fa-forward");

                     	jQuery( ".ui-icon.ui-icon-seek-end" ).wrap( "" );
 }
 function initAccountSearch(callbackFunction){

         $( ".search-customer" ).autocomplete({
                    delay: 500,
                    source: function( request, response ) {
                               $.ajax({
                                    url: "../customer/search",
                                    dataType: "json",
                                    data: {
                                      query: request.term
                                          },
                                     success: function( data ) {

                                           response($.map(data.customers, function(item) {
                                             return {
                                                        label: item.name +' ,'+item.address.city,
                                                        value: item.customerId,
                                                        customer:item,
                                                     }
                                               }));

                                             }
                                          }); },
                                 minLength: 2,
                                 select: callbackFunction
                      });


 }


    function actionFormat( cellvalue, options, rowObject ){
           	return "<button class='btn btn-xs btn-default btn-quick' data-toggle='modal' data-target='"+options.colModel.formatoptions.model+"' data-value='"+cellvalue+"' ><i class='fa "+options.colModel.formatoptions.icon+"'></i></button>";
            }
            function actionUnFormat( cellvalue, options, cell){
            	return $('img', cell).attr('src');
            }

   function resetForm($model) {

        var inputSelector = ':input:not([type="submit"], button):enabled:visible'


        $model.find('input:text, input:password, input:file, select, textarea').val('');
        $model.find('input:radio, input:checkbox')
                           .removeAttr('checked').removeAttr('selected');
       }
function initPOSModel(){


     $('.pos-model').on('hidden.bs.modal', function (event) {
          var modal = $(this)
          resetForm(modal);

      })

       $('.pos-model').on('hidden.bs.modal', function (event) {
          //alert("closed");
                var modal = $(this)
                resetForm(modal);

            });


     $('.pos-model').on('show.bs.modal', function (event) {

             var modal = $(this)

           var loadFunction=$(this).data("loader");

           console.log(loadFunction);
           var button = $(event.relatedTarget) // Button that triggered the modal

            var dataValue = button.data('value') // Extract info from data-* attributes

            if (typeof dataValue === "undefined") {

            }else{
               // loadFunction(productId,modal);
                myApp.showPleaseWait('div.modal-content:visible');

                window[loadFunction](dataValue,modal);
                  myApp.hidePleaseWait();
            }

      });

    $('.pos-model').find("form").on('submit', function (event) {

           event.preventDefault();
           var resetFlag = $(document.activeElement).data("reset");
           var $formObj= $(this);
            var $modelObj=  $formObj.closest( "div.pos-model");

           var options = {
                        url:       $formObj.attr('action') ,
                        type:      'post' ,
                        dataType:  'json' ,
                        clearForm: resetFlag  ,
                        resetForm: resetFlag  ,
                        timeout:   9000  ,
                        success:    function() {

                           myApp.hidePleaseWait();

                           var updater=$formObj.data("updater");
                           if(updater){
                                console.log("Updating the Grid:-"+updater);
                                $(updater).trigger("reloadGrid");
                                 myApp.hidePleaseWait();
                           }

                          if(!resetFlag)
                          {

                              $modelObj.modal('hide');
                            return;
                          }
                          else
                           {
                            myApp.showSuccess('div.modal-footer:visible');
                           }

                          }  ,
                       error:    function() {
                           myApp.hidePleaseWait();
                           myApp.showError('div.modal-footer:visible');

                       }
                   };

                   myApp.showPleaseWait('div.modal-content:visible');

          $formObj.ajaxSubmit(options) ;
          return false;

      });

}
var currencyformatoptions={decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "INR "};


